//定义插件
(function($) {
	//公共变量 
	var fastGridOpts;
	var tableDom; 
	var queryData;
	var curPage;
	
	$.fn.fastGrid = function(options) {    
	    fastGridOpts = $.extend({}, $.fn.fastGrid.defaults, options); 
	    queryData = getQueryObject(1);
	    queryData.pageSize=fastGridOpts.pageSize;
	    fastGridOpts.queryData = queryData;
	    tableDom = this;
	    //加载表格数据
	    loadList(tableDom,fastGridOpts);
	    //如果开启了删除功能则调用
	    if(fastGridOpts.batchDeleteSwitch){
	    	batchDelete(fastGridOpts.batchDeleteParam);
	    }
	    
	    //触发查询
	    $("#"+fastGridOpts.searchParam.searchBtnId).click(function(){
	    	 queryData = getQueryObject(1);
		     fastGridOpts.queryData = queryData;
	    	 loadList(tableDom,fastGridOpts);
	    });
	};    
	
	//默认参数
	$.fn.fastGrid.defaults = {    
	    url:"",//列表服务器请求地址
	    pageSize:10,//页长
	    queryData:{},//表格查询参数
	    templateId:"",//表格行模板ID
	    renderData:function(template,bean){},
	    loadSuccess:function(){},
	    batchDeleteSwitch:false,
	    doubleClickDetailFlag:true,
	    layerWindowSize:"",
	    batchDeleteParam:{
	    	url:"",
	    	actionBtnId:"",
	    	checkBoxName:""
	    },
	    searchParam:{//搜索表单相关参数
	    	formId:"",
	    	searchBtnId:""
	    },
	    singleDeleteUrl:"",
	    detailFlag:false,
	    loadDetailUrl:""
	}; 
	
	//加载列表
	function loadList($table,options){
		//加载层
		var index = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
		curPage = options.queryData.page;
		$table.prepend("<input type='hidden' id='curPage' value='"+curPage+"'>");
		var totalPage = 1;
		//结果总数
		var totalRecord = 0;
		$.ajax({
		    type : "post",
		    url : options.url,
		    data : options.queryData,
			cache : false,
			async : false,
			dataType : "json",
			success : function(jsonData){
				layer.close(index);
				totalPage = jsonData.totalPage;
				var records = jsonData.records;
			    totalRecord = jsonData.totalRecord;
				var listHtml = "";
				var template = $(options.templateId).html();
				if(records.length>0){
					$.each(records,function(i,bean){
						template = options.renderData(template,bean);
						//将全部null换成空串
						template = template.replace(new RegExp("null",'gm'),'')
						listHtml+=template;
						//模板重置
						template = $(options.templateId).html();
					});
					$table.find("tbody").html(listHtml);
				}else{
					$table.find("#defaultRow").html("<font color=red><b>暂无数据，请先进行添加操作！</b></font>");
				}
			}
		});
		$("#totalRecord").text(totalRecord);
		//初始分页条
	    initPage(curPage,totalPage);
	    //初始化删除操作
		$(tableDom).find(".deleteSingleData").click(function(){
			  var rowId = $(this).parent().parent().find("input[name='"+options.batchDeleteParam.checkBoxName+"']").val();
			  deleteRowById(options.singleDeleteUrl,rowId);
		});
		
		//初始化查看详情
		$(tableDom).find(".seeDetailData").click(function(){
			var rowId = $(this).parent().parent().find("input[name='"+options.batchDeleteParam.checkBoxName+"']").val();
			parent.layerWindow('查看明细',options.loadDetailUrl+"?id="+rowId,options.layerWindowSize);
		});
		
		//开启双击查看详情
		if(options.doubleClickDetailFlag){
			//初始化查看详情行上操作
			$(tableDom).find("tr").dblclick(function(){
				  var rowId = $(this).find("input[name='"+options.batchDeleteParam.checkBoxName+"']").val();
				  parent.layerWindow('查看明细',options.loadDetailUrl+"?id="+rowId);
			});
		}
		
		//初始化更新操作
		$(tableDom).find(".updateRowData").click(function(){
			 var rowId = $(this).parent().parent().find("input[name='"+options.batchDeleteParam.checkBoxName+"']").val();
			 parent.layerWindow('修改数据',options.loadDetailUrl+"?id="+rowId+"&actionType=update",options.layerWindowSize);
		});
		//完成后调用完成方法
		options.loadSuccess();
	}
	
	//初始化分页组件
	function initPage(page,totalPage){
		layui.use("laypage",function(){
			var laypage = layui.laypage;
			laypage({
				  cont: 'pageNav',
				  pages: totalPage,//总页数
				  curr:page,//当前页
				  groups:5,
				  skin: '#5A98DE',
				  skip: true,//是否开启跳页
				  first:"首页",//首页显示
				  last:"最后一页",
				  jump: function(obj, first){ //触发分页后的回调
				    if(!first){
				    	queryData = getQueryObject(obj.curr);
					    fastGridOpts.queryData = queryData;
				    	loadList(tableDom,fastGridOpts);
				    }
				  }
				});
		})
	}

	/**
	 * 获取查询对象
	 * @returns
	 */
	function getQueryObject(page){
	   var formId = fastGridOpts.searchParam.formId;
	   var searChObj = new Object();
	   $("#"+formId).find("input").each(function(i){
		   searChObj[$(this).attr("name")] = $(this).val();
	   });
	   
	   $("#"+formId).find("select").each(function(i){
		   searChObj[$(this).attr("name")] = $(this).val();
	   });
	   searChObj.page = page;
	   searChObj.pageSize = fastGridOpts.pageSize;
	   return searChObj;
	}
	
	//触发单个删除
	function deleteRowById(singleDeleteUrl,rowId){
		  //询问框
	  	  layer.confirm('确认删除吗？', {
	  	      btn: ['确认','取消'] //按钮
	  	  }, function(){
		  		var index = layer.load(1, {
		  		  shade: [0.1,'#fff'] //0.1透明度的白色背景
		  		});
	  		  //请求后台进行发标操作
	  		  $.post(singleDeleteUrl, {id:rowId},
	  			 function(data){
	 			     if(data.code=="00"){
	 			    	loadList(tableDom,fastGridOpts);
	 			    	layer.msg('删除操作成功......', {time: 500});
	 			    	layer.close(index);
		             }else{
		            	layer.msg(data.msg,{time: 1000});
		             }
		  	     },
		  	 "json");
	  	  }, function(){
		  	    layer.msg('取消中......', {
		  	       time: 500, //1s后自动关闭
		  	    });
	  	  });
	}
	
	/**
	 * 批量删除
	 * @param batchDeleteParam
	 * @returns{code:"00",data{},msg:""}
	 */
	function batchDelete(batchDeleteParam){
		$(batchDeleteParam.actionBtnId).click(function(){
			var boxChecked = $("input[name='"+batchDeleteParam.checkBoxName+"']:checked");
			  if(boxChecked.length>0){
			  //询问框
		  	  layer.confirm('确认删除吗？', {
		  	      btn: ['确认','取消'] //按钮
		  	  }, function(){
		  		  var ids = "";
		  		  $(boxChecked).each(function(i){
		  			  ids += $(this).val()+",";
		  		  })
		  		  ids = ids.substring(0,ids.lastIndexOf(","));
		  		  //请求后台进行发标操作
		  		  $.post(batchDeleteParam.url, {ids:ids},
		  			 function(data){
		 			     if(data.code=="00"){
		 			    	loadList(tableDom,fastGridOpts);
		 			    	layer.msg('删除操作成功......', {time: 500});
			             }else{
			            	layer.msg(data.msg, {time: 1000});
			             }
		  		  },"json");
		  	  }, function(){
			  	    layer.msg('取消中......', {
			  	       time: 500, //1s后自动关闭
			  	    });
		  	  });
			  }else{
				  layer.msg('温馨提示:此操作至少选中一项', {
		  	      time: 1000, //1s后自动关闭
		  	  });
			}
		})
	}
})(jQuery);
